package com.example.myapplication.soaprequest

import com.example.myapplication.soaprequest.response.SoapResponseBody
import com.example.mylibrary.utils.UiTools
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import retrofit2.HttpException
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException

interface CustomerObserverSoap : Observer<SoapEnvelop> {
    override fun onSubscribe(d: Disposable) {

    }

    override fun onNext(soapEnvelop: SoapEnvelop) {
        if (soapEnvelop.body == null) {
            onError(IllegalAccessException("请求信息有误,请检查后重试"))
            return
        }
        if (soapEnvelop.body is SoapResponseBody) {
            val result = (soapEnvelop.body as SoapResponseBody).value.result
            // 结果不为空且内容包含false, 说明请求数据错误,返回错误状态并提示
            if (result.isNotEmpty() && result.contains("false")) {
                val split = result.split(",")
                if (!split.isNullOrEmpty() && split.size > 1) {
                    onError(IllegalAccessException(split[1]))
                } else {
                    onError(IllegalAccessException(result))
                }
                return
            }
            onSuccess(result)
        }
    }

    override fun onError(e: Throwable) {
        when (e) {
            is SocketTimeoutException -> {  // 超时异常
                UiTools.showToast("连接超时,请检查网络设置")
            }
            is UnknownHostException,
            is HttpException,
            is ConnectException -> { // 网络地址错误异常
                UiTools.showToast("连接异常,请检查地址后重试")
            }
            is IllegalAccessException -> { // 自定义异常
                e.message?.let { UiTools.showToast(it) }
            }
        }
    }

    override fun onComplete() {

    }

    fun onSuccess(result: String)
}